package com.wwwarehouse.resource_center.fragment.sales_Inventory_statistics;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Interceptor;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.bean.carddesk.CardDeskMessageStableCardBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.fragment.CommonBasePagerFragment;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.resource_center.R;
import com.wwwarehouse.resource_center.bean.sales_inventory_statistics.CustomerSupplierResponseBean;
import com.wwwarehouse.resource_center.bean.sales_inventory_statistics.SalesInventoryStatisticsResponseBean;
import com.wwwarehouse.resource_center.constant.ResourceConstant;
import com.wwwarehouse.resource_center.eventbus_event.DDMDEvent;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import de.greenrobot.event.EventBus;

import static android.R.id.list;

/**
 * Created by Jackie 2017/10/26
 * 销售库存信息统计
 */
@Route(path = ResourceConstant.PATH_SALES_INVENTORY_STATISTICS)
public class SalesInventoryStatisticsListFragment extends CommonBasePagerFragment {

    public static final int PAGE = 1;
    public static final int SIZE = 7;  //一页显示7条

    private static final int REQUEST_GET_CUSTOMER_SUPPLIER = 0;
    private static final int REQUEST_GET_INVENTORY_STATISTICS = 1;

    private List<String> mBusinessUnitIds;

    protected int mSelectedBubblePosition = 1;


    private String orderColumn = "soldQty";
    private String orderType = "desc";
    private String itemSearch;
    private CustomerSupplierResponseBean customerSupplierResponseBean;
    private CustomerSupplierResponseBean selectedResponseBean;
    private String date;

    private boolean idAdd;

    @Override
    public void onRefreshListener() {

    }

    @Override
    public void onLoadSuccess(String data, int what) {
        switch (what) {
            case REQUEST_GET_CUSTOMER_SUPPLIER:
                //测试数据
//                String test = "{'customerBus': [{'customerBuId': 10001436, 'customerBuName': '测试数据显示09'}, {'customerBuId': 10001357, 'customerBuName': '测试公司二（IT）'}, {'customerBuId': 10001662, 'customerBuName': 'Testicyxdw0001'}, {'customerBuId': 10001633, 'customerBuName': '浙江省网仓科技有限公司'}, {'customerBuId': 10001554, 'customerBuName': '啊啊啊'}, {'customerBuId': 10001507, 'customerBuName': '我是谁'}], 'supplierBus': [{'supplierBuId': 10001677, 'supplierBuName': 'Shh'}, {'supplierBuId': 10001702, 'supplierBuName': 'Testicyxdw0001'}, {'supplierBuId': 10001703, 'supplierBuName': '背景资料伊拉克'}]}";
                customerSupplierResponseBean = JSON.parseObject(data, CustomerSupplierResponseBean.class);
                if (customerSupplierResponseBean != null)
                    mStateLayout.setEmptyListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getInventoryStatisticsInfo();
                        }
                    });

                getInventoryStatisticsInfo();
                break;
            case REQUEST_GET_INVENTORY_STATISTICS:
                mStateLayout.showContentView();
                SalesInventoryStatisticsResponseBean salesInventoryStatisticsResponseBean = JSON.parseObject(data, SalesInventoryStatisticsResponseBean.class);
                ArrayList<SalesInventoryStatisticsResponseBean.ListBean> salesInventoryStatisticsList = (ArrayList<SalesInventoryStatisticsResponseBean.ListBean>) salesInventoryStatisticsResponseBean.getList();

                try {
                    setData(salesInventoryStatisticsList.size(), 7, SalesInventoryStatisticsDetailsFragment.class.getName(), null, salesInventoryStatisticsList);

                    if (!idAdd) {
                        idAdd = true;
                        DeskDrawerMultipleDoubleFragment deskDrawerMultipleFragment = DeskDrawerMultipleDoubleFragment.newInstance("供货商", "发布对象", customerSupplierResponseBean, customerSupplierResponseBean.getSupplierBus(), 2);
                        ((BaseCardDeskActivity) mActivity).setDrawerLayout(deskDrawerMultipleFragment);
                        ((BaseCardDeskActivity) mActivity).disableDrawerLayout();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    LogUtils.showErrLog("error -----> " + e.getMessage());
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoadError(String s) {
        toast(s);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof SalesInventoryStatisticsListFragment)
            mActivity.setTitle(R.string.sales_inventory_statistics);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void requestDatas() {
        super.requestDatas();
        hideConfirmButton();
        EventBus.getDefault().register(this);

        mStateLayout.setEmptyListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCustomerSupplier();
            }
        });
        getCustomerSupplier();
    }

    /**
     * 获取客户列表
     */
    private void getCustomerSupplier() {
        Map map = new HashMap();

        map.put("relationType", "CUSTOMER");
        CardDeskMessageStableCardBean.TasksBean taskBean = getArguments().getParcelable("data");
        if (taskBean != null)
            mBusinessUnitIds = taskBean.getBusinessIds();
//        /***** 测试数据  ***/
//        mBusinessUnitIds.add("10001719");
//        mBusinessUnitIds.add("10001759");
        Set<String> set = new HashSet<>();
        for (String id : mBusinessUnitIds) {
            set.add(id);
        }
        Iterator<String> it = set.iterator();
        mBusinessUnitIds.clear();
        while (it.hasNext()) {
            mBusinessUnitIds.add(it.next());
        }

        map.put("supplierBuIds", mBusinessUnitIds);

        loadData(ResourceConstant.URL_GET_CUSTOMER_SUPPLIER, map, REQUEST_GET_CUSTOMER_SUPPLIER);
    }

    /**
     * 销售库存统计
     */
    private void getInventoryStatisticsInfo() {
        Map paramsMap = new HashMap();

        paramsMap.put("dataSet", "inventorySales");

        String time;
        if (TextUtils.isEmpty(date)) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            time = format.format(System.currentTimeMillis());
        } else {
            time = date;
        }

        List<String> customerList = new ArrayList<>();
        if (selectedResponseBean == null) {
            for (int i = 0; i < customerSupplierResponseBean.getCustomerBus().size(); i++) {
                customerList.add(customerSupplierResponseBean.getCustomerBus().get(i).getCustomerBuId());
            }
        } else {
            for (int i = 0; i < selectedResponseBean.getCustomerBus().size(); i++) {
                customerList.add(selectedResponseBean.getCustomerBus().get(i).getCustomerBuId());
            }
        }
        List<String> supplierList = new ArrayList<>();

        if (selectedResponseBean == null) {
            for (int i = 0; i < customerSupplierResponseBean.getSupplierBus().size(); i++) {
                supplierList.add(customerSupplierResponseBean.getSupplierBus().get(i).getSupplierBuId());
            }
        } else {
            for (int i = 0; i < selectedResponseBean.getSupplierBus().size(); i++) {
                supplierList.add(selectedResponseBean.getSupplierBus().get(i).getSupplierBuId());
            }
        }
        List<Map> filterList = new ArrayList<>();
        List<String> times = new ArrayList<>();
        times.add(time);
        Map validStartMap = new HashMap();
        validStartMap.put("column", "validStartTime");
        validStartMap.put("type", "<=");
        validStartMap.put("values", times);
        filterList.add(validStartMap);

        Map validEndMap = new HashMap();
        validEndMap.put("column", "validEndTime");
        validEndMap.put("type", ">=");
        validEndMap.put("values", times);
        filterList.add(validEndMap);

        if (supplierList.size() > 0) {
            Map supplierMap = new HashMap();
            supplierMap.put("column", "supplierId");
            supplierMap.put("type", "in");
            supplierMap.put("values", supplierList);
            filterList.add(supplierMap);
        }

        if (!TextUtils.isEmpty(itemSearch)) {
            List<String> searchList = new ArrayList<>();
            searchList.add(itemSearch);
            Map itemSearchMap = new HashMap();
            itemSearchMap.put("column", "itemSearch");
            itemSearchMap.put("type", "like");
            itemSearchMap.put("values", searchList);
            filterList.add(itemSearchMap);
        }

        if (customerList.size() > 0) {
            Map demanderMap = new HashMap();
            demanderMap.put("column", "demanderId");
            demanderMap.put("type", "in");
            demanderMap.put("values", customerList);
            filterList.add(demanderMap);

        }
        paramsMap.put("filters", filterList);
        //排序
        Map orderMap = new HashMap();
        orderMap.put("column", orderColumn);
        orderMap.put("type", orderType);

        List<Map> orders = new ArrayList<>();
        orders.add(orderMap);
        paramsMap.put("orders", orders);
        List<String> selects = new ArrayList();
        selects.add("itemCode");
        selects.add("itemUrl");
        selects.add("validQty");
        selects.add("soldQty");
        selects.add("validRatio");
        paramsMap.put("selects", selects);
        paramsMap.put("page", PAGE);
        paramsMap.put("size", 9999);
        paramsMap.put("ifCount", true);

        /***测试数据***/
//        JSONObject jsonObject = JSON.parseObject("{ \"size\": \"21\", \"ifCount\":\"true\", \"selects\": [\"itemCode\", \"itemUrl\", \"validQty\", \"soldQty\", \"validRatio\"], \"filters\": [ { \"type\": \"in\", \"values\": [\"10001719\"], \"column\": \"supplierId\" } ], \"orders\": [{ \"type\": \"desc\", \"column\": \"soldQty\" }], \"dataSet\": \"inventorySales\", \"page\": 1 }");
        loadData(ResourceConstant.URL_GET_INVENTORY_STATISTICS, paramsMap, REQUEST_GET_INVENTORY_STATISTICS);
    }

    /**
     * 1.已售数量由高到低
     * <p>
     * 2.可用数量由高到低
     * <p>
     * 3.可用占比由高到低
     */
    @Override
    public void sortClick(View anchor) {
        super.sortClick(anchor);
        if (peekFragment() instanceof SalesInventoryStatisticsListFragment) {
            PopUpUtils.showBubbleInviteSort(mActivity, anchor, mSelectedBubblePosition, new PopUpUtils.OnChoiceListener() {
                @Override
                public void onChoice(int position) {
                    mSelectedBubblePosition = position;
                    switch (position) {
                        case 1:
                            orderColumn = "soldQty";
                            break;
                        case 2:
                            orderColumn = "validQty";
                            break;
                        case 3:
                            orderColumn = "validRatio";
                            break;
                        default:
                            break;
                    }

                    getInventoryStatisticsInfo();
                }
            }, getString(R.string.resource_quantity_sold_desc), getString(R.string.resource_number_available_desc), getString(R.string.resource_available_than_desc));
        }
    }

    @Override
    public void searchNoRealTimeClick(String text) {
        if (peekFragment() instanceof SalesInventoryStatisticsListFragment) {
            itemSearch = text;
            getInventoryStatisticsInfo();
        }
    }

    @Override
    public void cancelClick() {
        super.cancelClick();
        if (peekFragment() instanceof SalesInventoryStatisticsListFragment) {
            itemSearch = null;
            getInventoryStatisticsInfo();
        }
    }

    @Override
    public void filterClick() {
        if (peekFragment() instanceof SalesInventoryStatisticsListFragment) {
            ((BaseCardDeskActivity) mActivity).showDrawerLayout();
        }
    }

    public void onEventMainThread(DDMDEvent event) {
        if (peekFragment() instanceof SalesInventoryStatisticsListFragment) {
            date = event.getMsg();
            selectedResponseBean = event.getmFilterList();
            getInventoryStatisticsInfo();
        }
    }
}
